
/// 程序中的错误码
enum Code {
  success(code: 1, msg: 'Request success'),
  failure(code: 0, msg: 'Request failure'),
  error(code: -2, msg: 'Request error, please try again later');

  const Code({required this.code, required this.msg});

  final int code;
  final String msg;
}

var defaultSuccessBaseEntity = BaseEntity.createSuccess();
var defaultFailureBaseEntity = BaseEntity.createFailure();

/// 统一的实体类
class BaseEntity {
  BaseEntity(this.code, this.info, this.data);

  // 后台返回的状态码（1：成功 其他：失败）
  late int code;
  String? info;
  dynamic data;

  factory BaseEntity.fromJson(Map<String, dynamic> json) => BaseEntity(
        json['code'] as int,
        json['info'] as String?,
        json['data'] as dynamic,
      );

  Map<String, dynamic> toJson() => <String, dynamic>{
        'code': code,
        'info': info,
        'data': data,
      };

  /// 是否成功
  bool get isSuccess => code == Code.success.code;

  /// 创建成功对象
  static BaseEntity createSuccess({
    int? code,
    String? msg,
    dynamic data,
  }) =>
      BaseEntity(code ?? Code.success.code, msg ?? Code.success.msg, data);

  /// 创建失败对象
  static BaseEntity createFailure({
    int? code,
    String? msg,
    dynamic data,
  }) =>
      BaseEntity(code ?? Code.failure.code, msg ?? Code.failure.msg, data);
}
